﻿using Cdx.Common.Contracts;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Cdx.Mock.DocumentManager
{
    public class DocumentManagerService : IDocumentManager
    {
        private static string m_Folder;
        
        static DocumentManagerService()
        {
            m_Folder = Path.Combine(Environment.CurrentDirectory, "Docs");

            if (Directory.Exists(m_Folder) == false)
            {
                Directory.CreateDirectory(m_Folder);
            }
        }
        
        public string AddDocument(string userId, string fileName)
        {
            return AddDocument(userId, File.ReadAllBytes(fileName));
        }

        public string AddDocument(string userId, byte[] file)
        {
            var folder = Path.Combine(m_Folder, userId);

            if (Directory.Exists(folder) == false)
            {
                Directory.CreateDirectory(folder);
            }


            Guid fileID = Guid.NewGuid();
            File.WriteAllBytes(Path.Combine(folder, fileID.ToString()), file); 
            
            return fileID.ToString();
        }

        public byte[] GetDocument(string documentID)
        {
            var fileName = Directory.GetFiles(m_Folder, documentID)[0];

            return File.ReadAllBytes(fileName);
        }
    }
}
